package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.CartCheckoutVo;
import com.cskaoyan.market.vo.CartVo;
import com.cskaoyan.market.vo.CheckOutVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxCartServiceImpl implements WxCartService {

    MarketCart cart = new MarketCart();

    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketGoodsAmountMapper goodsAmountMapper;
    @Autowired
    MarketCheckedGoodsAmountMapper checkedGoodsAmountMapper;
    @Autowired
    MarketGoodsSpecificationMapper getGoodsSpecificationMapper;
    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Autowired
    MarketGoodsCountMapper goodsCountMapper;

    @Override
    public int goodsCount(Integer userId) {
        Integer goodsCount = 0;
        if (userId != 0) {
            goodsCount = goodsCountMapper.goodsCount(userId);
        }
        return goodsCount;
    }

    @Override
    public int add(Integer goodsId, Integer number, Integer productId, Integer userId) {

        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);

        //判断购物车内是否已有这件商品
        //购物车中已经存在
        for (MarketCart marketCart : marketCarts) {
            if (marketCart.getProductId().equals(productId)) {

                MarketCartExample cartExample1 = new MarketCartExample();
                cartExample1.or().andProductIdEqualTo(productId);
                MarketCart cart1 = cartMapper.selectOneByExample(cartExample1);

                cart1.setNumber(((short) (cart1.getNumber() + number)));
                cartMapper.updateByExample(cart1, cartExample1);

                return goodsCount(userId);
            }
        }

        //购物车中不存在
        //在goods表中查询
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);

        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        goodsSpecificationExample.or().andGoodsIdEqualTo(goodsId);
        MarketGoodsSpecification goodsSpecification = goodsSpecificationMapper.selectOneByExample(goodsSpecificationExample);
        String[] specification = new String[2];
        specification[0] = goodsSpecification.getSpecification();
        specification[1] = goodsSpecification.getValue();

        String goodsSn = goods.getGoodsSn();
        String goodsName = goods.getName();
        BigDecimal retailPrice = goods.getRetailPrice();
        String picUrl = goods.getPicUrl();

        cart.setUserId(userId);
        cart.setGoodsId(goodsId);
        cart.setNumber(number.shortValue());
        cart.setProductId(productId);
        cart.setGoodsSn(goodsSn);
        cart.setGoodsName(goodsName);
        cart.setPrice(retailPrice);
        cart.setPicUrl(picUrl);
        cart.setSpecifications(specification);
        cart.setChecked(false);
        cart.setAddTime(LocalDateTime.now());
        cart.setUpdateTime(LocalDateTime.now());
        cart.setDeleted(false);
        cartMapper.insert(cart);

        return goodsCount(userId);

    }

    @Override
    public Map<String, Object> index(Integer userId) {

        //cartList
        Map<String, Object> result = new HashMap<>();

        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andUserIdEqualTo(userId);
        List<MarketCart> cartList = cartMapper.selectByExample(cartExample);
        result.put("cartList", cartList);

        //cartTotal
        CartVo cartVo = new CartVo();

        Integer checkedGoodsCount = 0;
        if (userId != 0) {
            checkedGoodsCount = goodsCountMapper.goodsCheckedCount(userId);
        }
        if (checkedGoodsCount == null) {
            checkedGoodsCount = 0;
        }

        Integer goodsCount = 0;
        if (userId != 0) {
            goodsCount = goodsCountMapper.goodsCount(userId);
        }

        BigDecimal checkedAmount = checkedGoodsAmountMapper.countCheckedAmount();
        BigDecimal countAmount = goodsAmountMapper.countAmount();
        if (checkedAmount == null) {
            checkedAmount = BigDecimal.ZERO;
        }

        cartVo.setCheckedGoodsAmount(checkedAmount);
        cartVo.setCheckedGoodsCount(checkedGoodsCount);
        cartVo.setGoodsAmount(countAmount);
        cartVo.setGoodsCount(goodsCount);
        result.put("cartTotal", cartVo);

        return result;
    }

    @Override
    public int update(Integer goodsId, short number, Integer productId, Integer id, Integer userId) {

        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andIdEqualTo(id);

        cart.setId(id);
        cart.setUserId(userId);
        cart.setGoodsId(goodsId);
        cart.setNumber(number);
        cart.setProductId(productId);

        //在goods表中查询
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        String goodsSn = goods.getGoodsSn();
        String goodsName = goods.getName();
        BigDecimal retailPrice = goods.getRetailPrice();
        String picUrl = goods.getPicUrl();

        cart.setGoodsSn(goodsSn);
        cart.setGoodsName(goodsName);
        cart.setPrice(retailPrice);
        cart.setPicUrl(picUrl);
        cart.setChecked(false);
        cart.setUpdateTime(LocalDateTime.now());
        cart.setDeleted(false);
        cartMapper.updateByExample(cart, cartExample);

        return 200;
    }

    @Override
    public Object checked(Integer isChecked, List<Integer> productIds, Integer userId) {

        for (Integer productId : productIds) {
            if (productId == 0) {
                continue;
            }
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.or().andProductIdEqualTo(productId);
            MarketCart cart = cartMapper.selectOneByExample(cartExample);
            if (isChecked == 1) {
                //未选中，把isChecked变成1
                cart.setChecked(true);
            } else if (isChecked == 0) {
                //选中，把isChecked变成0
                cart.setChecked(false);
            }
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
        return index(userId);
    }

    @Override
    public int fastAdd(Integer goodsId, short number, Integer productId, Integer userId) {

        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andProductIdEqualTo(productId).andGoodsIdEqualTo(goodsId);
        MarketCart marketCart = cartMapper.selectOneByExample(cartExample);

        marketCart.setNumber(number);
        cartMapper.updateByExample(marketCart, cartExample);
        return 200;
    }

    @Override
    public CheckOutVo getCheckoutList(Integer addressId, Integer couponId, Integer userCouponId, Integer userId) {
        CheckOutVo checkOutVo = new CheckOutVo();
        checkOutVo.setAddressId(addressId);
        checkOutVo.setCouponId(couponId);

        MarketAddressExample marketAddressExample = new MarketAddressExample();
        marketAddressExample.or().andIdEqualTo(addressId);
        MarketAddress marketAddress = addressMapper.selectOneByExample(marketAddressExample);
        checkOutVo.setCheckedAddress(marketAddress);

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.or().andCheckedEqualTo(true).andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = cartMapper.selectByExample(marketCartExample);
        checkOutVo.setCheckedGoodsList(marketCarts);

        BigDecimal goodsTotalPrice = new BigDecimal("0");
        for (MarketCart marketCart : marketCarts) {
            BigDecimal bigDecimal = shortToBigDecimal(marketCart.getNumber());
            BigDecimal multiply = marketCart.getPrice().multiply(bigDecimal);
            goodsTotalPrice = goodsTotalPrice.add(multiply);
        }

        checkOutVo.setGoodsTotalPrice(goodsTotalPrice);

        MarketSystemExample marketSystemExample = new MarketSystemExample();
        marketSystemExample.or().andKeyNameEqualTo("market_express_freight_min");
        MarketSystem marketSystem = systemMapper.selectOneByExampleSelective(marketSystemExample, MarketSystem.Column.keyValue);
        String keyValue = marketSystem.getKeyValue();
        BigDecimal keyvalue = new BigDecimal(keyValue);
        if (goodsTotalPrice.compareTo(keyvalue) >= 0) {
            BigDecimal bigDecimal = new BigDecimal("0");
            checkOutVo.setFreightPrice(bigDecimal);
        } else {
            MarketSystemExample marketSystemExample1 = new MarketSystemExample();
            marketSystemExample1.or().andKeyNameEqualTo("market_express_freight_value");
            MarketSystem marketSystem1 = systemMapper.selectOneByExampleSelective(marketSystemExample1, MarketSystem.Column.keyValue);
            String keyValue1 = marketSystem1.getKeyValue();
            BigDecimal bigDecimal = new BigDecimal(keyValue1);
            checkOutVo.setFreightPrice(bigDecimal);
        }

        BigDecimal orderTotalPrice = checkOutVo.getFreightPrice().add(checkOutVo.getGoodsTotalPrice());
        checkOutVo.setOrderTotalPrice(orderTotalPrice);

        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.or().andIdEqualTo(couponId);
        MarketCoupon marketCoupon = couponMapper.selectOneByExampleSelective(marketCouponExample, MarketCoupon.Column.discount);


        BigDecimal discount = new BigDecimal(0);
        if (marketCoupon == null) {
            marketCoupon = new MarketCoupon();
            marketCoupon.setDiscount(new BigDecimal("0"));
            discount = marketCoupon.getDiscount();
        } else {
            discount = marketCoupon.getDiscount();
        }


        checkOutVo.setCouponPrice(discount);
        checkOutVo.setActualPrice(orderTotalPrice.subtract(discount));

        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.or().andCouponIdEqualTo(couponId).andUserIdEqualTo(userId);
        MarketCouponUser marketCouponUsers = couponUserMapper.selectOneByExample(marketCouponUserExample);

        Integer couponUserId = 0;
        if (marketCouponUsers == null) {
            marketCouponUsers = new MarketCouponUser();
            marketCouponUsers.setId(0);
            Integer id = marketCouponUsers.getId();
        } else {
            couponUserId = marketCouponUsers.getId();
        }
        checkOutVo.setUserCouponId(couponUserId);


        MarketCouponUserExample marketCouponUserExample1 = new MarketCouponUserExample();
        marketCouponUserExample.or().andUserIdEqualTo(userId);
        long l = couponUserMapper.countByExample(marketCouponUserExample1);
        checkOutVo.setAvailableCouponLength((int) l);

        return checkOutVo;
    }

    public static BigDecimal shortToBigDecimal(Short s) {
        BigDecimal bigDecimal = new BigDecimal(s);
        return bigDecimal;
    }

    @Override
    public Object delete(List<Integer> productIds, Integer userId) {

        for (Integer productId : productIds) {
            if (productId == 0) {
                continue;
            }
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.or().andProductIdEqualTo(productId);
            MarketCart cart = cartMapper.selectOneByExample(cartExample);

            cartMapper.deleteByExample(cartExample);
        }
        return index(userId);
    }
}
